<?php
/**
 *
 * @author junsion
 * @url 
 */
defined('IN_IA') or exit('Access Denied');

class junsion_wifinavModuleWxapp extends WeModuleWxapp {
	public function doPageOpenid(){
		global $_GPC, $_W;
		$account_api = WeAccount::create();
		$oauth = $account_api->getOauthInfo($_GPC['code']);
		$weid = $_W['uniacid'];
		$item = pdo_fetch('select id from '.tablename($this->modulename.'_user')." where openid='{$oauth['openid']}' and weid='{$weid}'");
		if (empty($item)){
			pdo_insert($this->modulename.'_user',array(
					'weid' => $weid,
					'openid' => $oauth['openid'],
					'realname' => '用户'.date('Ymd').random(5,1),
					'avatar' => $_W['siteroot'].'addons/junsion_wifinav/resource/people_fill.png',
					'gender' => 1,
					'createtime' => time()
			));
		}
		echo $oauth['openid'];
	}
	
	public function doPageupdateUser(){
		global $_GPC, $_W;
		$weid = $_W['uniacid'];
		$openid = $_GPC['openid'];
		$item = pdo_fetch('select id,isupdate from '.tablename($this->modulename.'_user')." where openid='{$openid}' and weid='{$weid}'");
		if (!empty($item)){
			if ($_GPC['nickname']) $data['nickname'] = $_GPC['nickname'];
			if ($_GPC['realname']) $data['realname'] = $_GPC['realname'];
			if ($_GPC['avatar']) $data['avatar'] = $_GPC['avatar'];
			if ($_GPC['gender']) $data['gender'] = $_GPC['gender'];
			if ($_GPC['mobile']) $data['mobile'] = $_GPC['mobile'];
			if ($_GPC['address']) $data['address'] = $_GPC['address'];
			if ($_GPC['introduce']) $data['introduce'] = $_GPC['introduce'];
			if(empty($item['isupdate'])){
				if($data['realname']){
					$data['isupdate'] = 1;
				}elseif ($data['nickname']){
					$data['realname'] = $data['nickname'];
					$data['isupdate'] = 1;
				}
			}
			if ($data) pdo_update($this->modulename.'_user',$data,array('id'=>$item['id']));
		}
		echo $item['id'];
	}
	
	public function doPageEnter(){
		global $_GPC,$_W;
		$op = $_GPC['op'];
		$weid = $_W['uniacid'];
		if($op == 'getPic'){
			$cfg = $this->module['config']['enter'];
			$result = array();
			if ($cfg['enter_1']) $result['enter_1'] = toimage($cfg['enter_1']);
			if ($cfg['enter_2']) $result['enter_2'] = toimage($cfg['enter_2']);
			if ($cfg['enter_3']) $result['enter_3'] = toimage($cfg['enter_3']);
			$packages = pdo_fetchall('select id,title,price from '.tablename($this->modulename.'_package')." where weid='{$weid}' order by id asc");
			if ($packages){
				foreach ($packages as $value){
					$list[] = array(
							'id' => $value['id'],
							'title' => $value['title'].' (￥'.$value['price'].')',
					);
				}
				$result['packages'] = $list;
			}
			$result['title'] = $this->module['config']['word']['enter'];
			echo json_encode($result);
			exit;
		}
		if($op == 'getPic2'){
			$cfg = $this->module['config']['enter'];
			$result = array();
			if ($cfg['enter_4']) $result['enter_4'] = toimage($cfg['enter_4']);
			if ($cfg['enter_5']) $result['enter_5'] = toimage($cfg['enter_5']);
			if ($cfg['enter_6']) $result['enter_6'] = toimage($cfg['enter_6']);
			$packages = pdo_fetchall('select id,title,price from '.tablename($this->modulename.'_apps')." where weid='{$weid}' order by id asc");
			if ($packages){
				foreach ($packages as $value){
					$list[] = array(
							'id' => $value['id'],
							'title' => $value['title'].' (￥'.$value['price'].')',
					);
				}
				$result['packages'] = $list;
			}
			$result['title'] = $this->module['config']['word']['enter2'];
			echo json_encode($result);
			exit;
		}
		if($op == 'getWifi'){
			$id = $_GPC['id'];
			$wifi = pdo_fetch('select * from '.tablename($this->modulename.'_list')." where weid='{$weid}' and id='{$id}'");
			$wif['advPic'] = $wif['newAdvPic']?$wif['newAdvPic']:$wifi['advPic'];
			unset($wifi['newAdvPic']);
			if (!$wifi['advPic']) unset($wifi['advPic']);
			else{
				$img = getimagesize($wifi['advPic']);
				$wifi['width'] = $img[0];
				$wifi['height'] = $img[1];
			}
			if ($wifi){
				die(json_encode(array('code'=>1,'wifi'=>$wifi)));
			}else{
				die(json_encode(array('code'=>0,'msg'=>'wifi不存在')));
			}
		}
		if($op == 'getApp'){
			$id = $_GPC['id'];
			$applet = pdo_fetch('select * from '.tablename($this->modulename.'_applet')." where weid='{$weid}' and id='{$id}'");
			if ($applet){
				die(json_encode(array('code'=>1,'app'=>$applet)));
			}else{
				die(json_encode(array('code'=>0,'msg'=>'小程序不存在')));
			}
		}
		if($op == 'addList'){
			$realname = $_GPC['realname'];
			$mobile = $_GPC['mobile'];
			$openid = $_GPC['openid'];
			$BSSID = $_GPC['BSSID'];
			$SSID = $_GPC['SSID'];
			$psw = $_GPC['psw'];
			$stitle = $_GPC['stitle'];
			$id = $_GPC['id'];
			$user = pdo_fetch('select id from '.tablename($this->modulename.'_user')." where openid='{$openid}' and weid='{$weid}'");
			if(empty($user)){
				echo json_encode(array('code'=>0,'msg'=>'用户不存在'));
				exit;
			}elseif (empty($realname)){
				echo json_encode(array('code'=>0,'msg'=>'请输入姓名'));
				exit;
			}elseif (empty($mobile)){
				echo json_encode(array('code'=>0,'msg'=>'请输入电话'));
				exit;
			}elseif (empty($stitle)){
				echo json_encode(array('code'=>0,'msg'=>'请输入店名'));
				exit;
			}elseif($id){
				$w = pdo_fetch('select id from '.tablename($this->modulename.'_list')." where id='{$id}' and weid='{$weid}'");
				if (empty($w)){
					echo json_encode(array('code'=>0,'msg'=>'WiFi不存在'));
					exit;
				}
				if (empty($SSID)){
					echo json_encode(array('code'=>0,'msg'=>'请输入WiFi名'));
					exit;
				}
			}elseif (empty($BSSID) && !$id){
				echo json_encode(array('code'=>0,'msg'=>'请选择WiFi'));
				exit;
			}
			
			$autoaudit = $this->module['config']['autoaudit'];
			if ($id){
				$isAdv = $_GPC['isAdv'];
				$data = array(
						'realname' => $realname,
						'mobile' => $mobile,
						'SSID' => $SSID,
						'stitle' => $stitle,
						'password' => $psw,
				);
				if ($isAdv==0){
					$data['advPic'] = '';
					$data['newAdvPic'] = '';
				}
				pdo_update($this->modulename.'_list',$data,array('id'=>$id));
				echo json_encode(array('code'=>1,'msg'=>'保存成功'));
			}else{
				$item = pdo_fetch('select id,uid from '.tablename($this->modulename.'_list')." where BSSID='{$BSSID}' and weid='{$weid}'");
				if($item){
					if ($item['uid']){
						echo json_encode(array('code'=>0,'msg'=>'该WiFi已申请入驻了'));
						exit;
					}else{
						pdo_delete($this->modulename.'_list',array('BSSID'=>$BSSID,'weid'=>$weid));
					}
				}
				pdo_insert($this->modulename.'_list',array(
						'realname' => $realname,
						'uid' => $user['id'],
						'mobile' => $mobile,
						'BSSID' => $BSSID,
						'SSID' => $SSID,
						'stitle' => $stitle,
						'password' => $psw,
						'status' => $autoaudit?1:0,
						'weid' => $weid
				));
				echo json_encode(array('code'=>1,'msg'=>'添加成功'));
			}
			exit;
		}
	}
	
	//入驻下单支付广告图
	public function doPageUpload(){
		global $_W,$_GPC;
	
		$weid = $_W['uniacid'];
		//判断WiFi是否已经入驻
		$realname = $_GPC['realname'];
		$mobile = $_GPC['mobile'];
		$openid = $_GPC['openid'];
		$BSSID = $_GPC['BSSID'];
		$SSID = $_GPC['SSID'];
		$psw = $_GPC['psw'];
		$stitle = $_GPC['stitle'];
		$pid = $_GPC['pid'];
		$id = $_GPC['id'];
		$user = pdo_fetch('select id,parentid from '.tablename($this->modulename.'_user')." where openid='{$openid}' and weid='{$weid}'");
		if(empty($user)){
			echo json_encode(array('code'=>2,'msg'=>'用户不存在'));
			exit;
		}elseif (empty($realname)){
			echo json_encode(array('code'=>2,'msg'=>'请输入姓名'));
			exit;
		}elseif (empty($mobile)){
			echo json_encode(array('code'=>2,'msg'=>'请输入电话'));
			exit;
		}elseif (empty($stitle)){
			echo json_encode(array('code'=>2,'msg'=>'请输入店名'));
			exit;
		}elseif ($id){
			$w = pdo_fetch('select id,advPic,newAdvPic,BSSID,endtime from '.tablename($this->modulename.'_list')." where id='{$id}' and weid='{$weid}'");
			if (empty($w)){
				echo json_encode(array('code'=>0,'msg'=>'WiFi不存在'));
				exit;
			}
			if (empty($SSID)){
				echo json_encode(array('code'=>0,'msg'=>'请输入WiFi名'));
				exit;
			}
			$BSSID = $w['BSSID'];
		}elseif(!$id){
			if (empty($BSSID)){
				echo json_encode(array('code'=>2,'msg'=>'请选择WiFi'));
				exit;
			}
			$item = pdo_fetch('select id,uid,endtime from '.tablename($this->modulename.'_list')." where BSSID='{$BSSID}' and weid='{$weid}'");
			if($item){
				if ($item['uid']){
					echo json_encode(array('code'=>2,'msg'=>'该WiFi已申请入驻了'));
					exit;
				}else{
					pdo_delete($this->modulename.'_list',array('BSSID'=>$BSSID,'weid'=>$weid));
				}
			}
		}
		if (!$w['advPic'] && !$w['newAdvPic']){
			if (empty($pid)){
				echo json_encode(array('code'=>2,'msg'=>'请选择套餐'));
				exit;
			}
			$p = pdo_fetch('select id,price,day from '.tablename($this->modulename.'_package')." where id='{$pid}'");
			if (!$p['id']){
				echo json_encode(array('code'=>2,'msg'=>'不存在该套餐'));
				exit;
			}
		}
		$file = $_FILES['photo'];
		$rand = random(10).time();
		$path = IA_ROOT.'/addons/junsion_wifinav/pics/';
		if (!file_exists($path)){
			mkdir($path,0777);
		}
		$url = $path.$rand.".jpg";
		$img = '../addons/junsion_wifinav/pics/'.$rand.".jpg";
		$cfg = $this->module['config'];
		if (move_uploaded_file($file['tmp_name'],$url)){
			$img = toimage($img);
			if ($cfg['qiniu']['isqiniu']){//七牛存储
				$img = $this->uploadQiniu($img,$cfg['qiniu'],'.jpg');
				unlink($url);
			}elseif (!empty($_W['setting']['remote']['type'])) { // 判断系统是否开启了远程附件
				$rand = random(10).time();
				$filename = $rand."pic.jpg";
				load()->func('file');
				$dir = ATTACHMENT_ROOT."images/";
				rename($url, $dir.$filename);
				file_remote_upload('images/'.$filename); //上传图片到远程
				$img = tomedia('images/'.$filename);
				unlink($url);
			}
			
			$cfg = $this->module['config'];
			$autoaudit = $cfg['autoaudit'];
			$day = $p['day'];
			/* 已付款过编辑入驻 */
			if ($w['advPic'] || $w['newAdvPic']){
				pdo_update($this->modulename.'_list',array(
						'realname' => $realname,
						'mobile' => $mobile,
						'SSID' => $SSID,
						'stitle' => $stitle,
						'password' => $psw,
						'newAdvPic' => $img,
						'advStatus' => 0,
						'day' => $day
				),array('id'=>$id));
				if ($autoaudit){
					$time = time();
					if($time<$w['endtime']){
						//未过期
						$t = $day*24*3600;
						pdo_query('update '.tablename($this->modulename.'_list')." set endtime = endtime + {$t}, day=0 where id='{$id}'");
					}else{
						//已过期
						$t = strtotime('+ '.$day.'day');
						pdo_query('update '.tablename($this->modulename.'_list')." set endtime = {$t}, day=0 where id='{$id}'");
					}
					pdo_update($this->modulename.'_list',array('advStatus'=>1,'advPic'=>$img,'newAdvPic'=>''),array('id'=>$id,'weid'=>$weid));
				}
				echo json_encode(array('code'=>11));
				exit;
			}

			$order = array(
					'realname' => $realname,
					'uid' => $user['id'],
					'mobile' => $mobile,
					'stitle' => $stitle,
					'BSSID' => $BSSID,
					'SSID' => $SSID,
					'password' => $psw,
					'fee' => $p['price'],
					'status' => $p['price'] > 0?0:1,
					'weid' => $weid,
					'pid' => $pid,
					'advPic' => $img,
					'paytime'=>time(),
					'ordersn' => date('YmdHis').random(5,1)
			);
			if ($order['fee']>0 && $cfg['distributor']['rate']>0){
				if ($user['parentid']>0){
					$order['parentid'] = $user['parentid'];
					$order['commission'] = intval($order['fee']*$cfg['distributor']['rate'])/100;
				}
			}
			
			if ($w) $order['type'] = 1;
			pdo_insert($this->modulename.'_order',$order);
			if ($order['fee'] == 0){
				if (!$w){
					$data = array(
						'realname' => $realname,
						'uid' => $order['uid'],
						'mobile' => $order['mobile'],
						'stitle' => $order['stitle'],
						'BSSID' => $order['BSSID'],
						'SSID' => $order['SSID'],
						'password' => $order['password'],
						'newAdvPic' => $order['advPic'],
						'advStatus' => 0,
						'day' => $day,
						'status' => $autoaudit?1:0,
						'weid' => $_W['uniacid'],
					);
					pdo_insert($this->modulename.'_list',$data);
					$id = pdo_insertid();
				}else{
					pdo_update($this->modulename.'_list',array(
							'realname' => $realname,
							'mobile' => $mobile,
							'stitle' => $stitle,
							'SSID' => $SSID,
							'password' => $psw,
							'newAdvPic' => $img,
							'day' => $day,
							'advStatus' => 0,
					),array('id'=>$id));
				}
				if ($autoaudit){
					$time = time();
					if($time<$w['endtime']){
						//未过期
						$t = $day*24*3600;
						pdo_query('update '.tablename($this->modulename.'_list')." set endtime = endtime + {$t}, day=0 where id='{$id}'");
					}else{
						//已过期
						$t = strtotime('+ '.$day.'day');
						pdo_query('update '.tablename($this->modulename.'_list')." set endtime = {$t}, day=0 where id='{$id}'");
					}
					pdo_update($this->modulename.'_list',array('advStatus'=>1,'advPic'=>$img,'newAdvPic'=>''),array('id'=>$id,'weid'=>$weid));
				}
				echo json_encode(array('code'=>10,'d'=>$day));
				exit;
			}
			$result = $this->unifiedOrder($openid,'入驻WiFi支付广告费用',$order['fee'],$order['ordersn']);
			if ($result['errcode'] == 1){
				echo json_encode(array('code'=>1,'params'=>$result['params']));
			}else{
				echo json_encode(array('code'=>2,'msg'=>$result['errmsg']));
			}
		}else{
			echo json_encode(array('code'=>2,'msg'=>'保存图片失败'));
		}
		exit;
	}
	
	public function doPageUpload2(){
		global $_W,$_GPC;
	
		$weid = $_W['uniacid'];
		//判断WiFi是否已经入驻
		$realname = $_GPC['realname'];
		$mobile = $_GPC['mobile'];
		$openid = $_GPC['openid'];
		$title = $_GPC['title'];
		$des = $_GPC['des'];
		$pid = intval($_GPC['pid']);
		$id = intval($_GPC['id']);
		$oid = intval($_GPC['oid']);
		$aid = intval($_GPC['aid']);
		$user = pdo_fetch('select id,parentid from '.tablename($this->modulename.'_user')." where openid='{$openid}' and weid='{$weid}'");
		if(empty($user)){
			echo json_encode(array('code'=>2,'msg'=>'用户不存在'));
			exit;
		}
		if (!$oid){
			if (empty($realname)){
				echo json_encode(array('code'=>2,'msg'=>'请输入姓名'));
				exit;
			}elseif (empty($mobile)){
				echo json_encode(array('code'=>2,'msg'=>'请输入电话'));
				exit;
			}elseif (empty($title)){
				echo json_encode(array('code'=>2,'msg'=>'请输入小程序名字'));
				exit;
			}elseif (empty($des)){
				echo json_encode(array('code'=>2,'msg'=>'请输入小程序描述'));
				exit;
			}elseif ($id){
				$w = pdo_fetch('select id from '.tablename($this->modulename.'_applet')." where id='{$id}' and weid='{$weid}'");
				if (empty($w)){
					echo json_encode(array('code'=>0,'msg'=>'小程序不存在'));
					exit;
				}
			}elseif(!$id){
				$item = pdo_fetch('select id,uid,endtime from '.tablename($this->modulename.'_applet')." where title='{$title}' and weid='{$weid}'");
				if($item){
					echo json_encode(array('code'=>2,'msg'=>'该小程序已申请入驻了'));
					exit;
				}
			}
			if ($_GPC['isAdv']){
				if (empty($pid)){
					echo json_encode(array('code'=>2,'msg'=>'请选择套餐'));
					exit;
				}
				$p = pdo_fetch('select id,price,day from '.tablename($this->modulename.'_apps')." where id='{$pid}'");
				if (!$p['id']){
					echo json_encode(array('code'=>2,'msg'=>'不存在该套餐'));
					exit;
				}
			}
			$file = $_FILES['photo'];
		}else{
			if ($oid){
				$order = pdo_fetch("select aid from ".tablename($this->modulename."_aorder")." where id='{$oid}' and uid='{$user['id']}'");
				if (empty($order)){
					exit;
				} 
			}
			
			$file = $_FILES['qrcode'];
		}
		
		$rand = random(10).time();
		$path = IA_ROOT.'/addons/junsion_wifinav/pics/';
		if (!file_exists($path)){
			mkdir($path,0777);
		}
		$url = $path.$rand.".jpg";
		$img = '../addons/junsion_wifinav/pics/'.$rand.".jpg";
		$cfg = $this->module['config'];
		if (move_uploaded_file($file['tmp_name'],$url)){
			$img = toimage($img);
			if ($cfg['qiniu']['isqiniu']){//七牛存储
				$img = $this->uploadQiniu($img,$cfg['qiniu'],'.jpg');
				unlink($url);
			}elseif (!empty($_W['setting']['remote']['type'])) { // 判断系统是否开启了远程附件
				$rand = random(10).time();
				$filename = $rand."pic.jpg";
				load()->func('file');
				$dir = ATTACHMENT_ROOT."images/";
				rename($url, $dir.$filename);
				file_remote_upload('images/'.$filename); //上传图片到远程
				$img = tomedia('images/'.$filename);
				unlink($url);
			}
			
			if ($order || $oid){
				pdo_update($this->modulename."_applet",array('qrcode'=>$img),array('id'=>$order?$order['aid']:$aid));
				return;
			}
				
			$cfg = $this->module['config'];
			$day = $p['day'];
			
			$data = array(
				'uid' => $user['id'],
				'title' => $title,
				'cid' => $cid,
				'thumb' => $img,
				'des' => $des,
				'endtime' => $day*24*3600 + time(),
				'status' => $p['price']>0?-1:0,
				'type'=>2,
				'weid' => $_W['uniacid'],
			);
			pdo_insert($this->modulename.'_applet',$data);
			$aid = pdo_insertid();
			if ($_GPC['isAdv']){
				$order = array(
					'realname' => $realname,
					'aid' => $aid,
					'uid' => $user['id'],
					'mobile' => $mobile,
					'fee' => $p['price'],
					'status' => 0,
					'weid' => $weid,
					'pid' => $pid,
					'paytime'=>time(),
					'ordersn' => 'A'.date('YmdHis').random(5,1)
				);
					
				pdo_insert($this->modulename.'_aorder',$order);
				$oid = pdo_insertid();
				if ($order['fee'] == 0){
					pdo_update($this->modulename."_aorder",array('status'=>1),array('id'=>$oid));
					echo json_encode(array('code'=>10,'oid'=>$oid));
					exit;
				}
				$result = $this->unifiedOrder($openid,'小程序入驻费用',$order['fee'],$order['ordersn']);
				if ($result['errcode'] == 1){
					echo json_encode(array('code'=>1,'params'=>$result['params'],'oid'=>$oid));
				}else{
					echo json_encode(array('code'=>2,'msg'=>$result['errmsg']));
				}
			}else{
				echo json_encode(array('code'=>11,'aid'=>$aid));
				exit;
			}
		}else{
			echo json_encode(array('code'=>2,'msg'=>'保存图片失败'));
		}
		exit;
	}
	
	public function doPageappDistributor(){
		global $_W,$_GPC;
		$uid = $_GPC['uid'];
		$weid = $_W['uniacid'];
		$user = pdo_fetch('select id,distributor,openid from '.tablename($this->modulename."_user")." where id='{$uid}' and weid='{$weid}'");
		if (empty($user)) die(json_encode(array('code'=>0,'msg'=>'会员不存在'.$uid.'-'.$weid)));
		if (!empty($user['distributor'])) die(json_encode(array('code'=>0,'msg'=>'您已经申请过了，不需要重新申请！')));
		$distributor = $this->module['config']['distributor'];
		if ($distributor['price']>0){
			$order = array(
					'uid' => $user['id'],
					'fee' => $distributor['price'],
					'status' => 0,
					'type' => 2,
					'weid' => $weid,
					'ordersn' => date('YmdHis').random(5,1)
			);
			pdo_insert($this->modulename."_order",$order);
			$result = $this->unifiedOrder($user['openid'],'申请成为分销商费用',$order['fee'],$order['ordersn']);
			if ($result['errcode'] == 1){
				echo json_encode(array('code'=>2,'params'=>$result['params'],'msg'=>'支付成功'));
			}else{
				echo json_encode(array('code'=>0,'msg'=>$result['errmsg']));
			}
		}else{
			if ($distributor['autoaudit']==1){
				pdo_update($this->modulename."_user",array('distributor'=>2),array('id'=>$uid));
				die(json_encode(array('code'=>1,'msg'=>'您已经成功申请成为分销商！')));
			}else{
				pdo_update($this->modulename."_user",array('distributor'=>1),array('id'=>$uid));
				die(json_encode(array('code'=>1,'msg'=>'成功提交申请，请等待审核！')));
			}
		}
	}
	
	public function doPageSaveList(){
		global $_W,$_GPC;
		$id = $_GPC['id'];
		$wifi = pdo_fetch('select id from '.tablename($this->modulename.'_list')." where id='{$id}' and weid='{$_W['uniacid']}'");
		if (empty($wifi)){
			echo json_encode(array('code'=>2,'msg'=>'wifi不存在'));
			exit;
		}
		$file = $_FILES['photo'];
		$rand = random(10).time();
		$path = IA_ROOT.'/addons/junsion_wifinav/pics/';
		if (!file_exists($path)){
			mkdir($path,0777);
		}
		$url = $path.$rand.".jpg";
		$img = '../addons/junsion_wifinav/pics/'.$rand.".jpg";
		$cfg = $this->module['config'];
		if (move_uploaded_file($file['tmp_name'],$url)){
			$img = toimage($img);
			if ($cfg['qiniu']['isqiniu']){//七牛存储
				$img = $this->uploadQiniu($img,$cfg['qiniu'],'.jpg');
				unlink($url);
			}elseif (!empty($_W['setting']['remote']['type'])) { // 判断系统是否开启了远程附件
				$rand = random(10).time();
				$filename = $rand."pic.jpg";
				load()->func('file');
				$dir = ATTACHMENT_ROOT."images/";
				rename($url, $dir.$filename);
				file_remote_upload('images/'.$filename); //上传图片到远程
				$img = tomedia('images/'.$filename);
				unlink($url);
			}
			pdo_update($this->modulename.'_list',array('advPic'=>$img),array('id'=>$id));
			echo json_encode(array('code'=>1,'msg'=>'修改广告图成功','img' => $img));
		}else{
			echo json_encode(array('code'=>2,'msg'=>'保存图片失败'));
			exit;
		}
	}
	
	private function uploadQiniu($url,$cfg,$type = '.png'){//$url 要上传的图片的链接 $cfg 七牛参数
		global $_GPC, $_W;
		require_once IA_ROOT. '/addons/junsion_wifinav/qiniu.php';
		$cfg['url'] = $cfg['qiniuUrl'];
		$qiniu = new Qiniu();
		$res = $qiniu->save($url, $cfg,$type);
		return $res;
	}
	
	//续费
	public function doPageRenew(){
		global $_W,$_GPC;
	
		$weid = $_W['uniacid'];
		//判断WiFi是否已经入驻
		$openid = $_GPC['openid'];
		$idx = intval($_GPC['idx']);
		$pid = intval($_GPC['pid']);
		$user = pdo_fetch('select id,parentid from '.tablename($this->modulename.'_user')." where openid='{$openid}' and weid='{$weid}'");
		$item = pdo_fetch('select id,uid,endtime,BSSID,SSID from '.tablename($this->modulename.'_list')." where id='{$idx}'");
		$p = pdo_fetch('select id,price,day from '.tablename($this->modulename.'_package')." where id='{$pid}'");
		if(empty($user)){
			echo json_encode(array('code'=>2,'msg'=>'用户不存在'));
			exit;
		}elseif (empty($item)){
			echo json_encode(array('code'=>2,'msg'=>'请选择WiFi'));
			exit;
		}elseif (empty($pid)){
			echo json_encode(array('code'=>2,'msg'=>'请选择套餐'));
			exit;
		}elseif (empty($p)){
			echo json_encode(array('code'=>2,'msg'=>'套餐不存在'));
			exit;
		}

		$order = array(
				'uid' => $user['id'],
				'BSSID' => $item['BSSID'],
				'SSID' => $item['SSID'],
				'status' =>0,
				'weid' => $weid,
				'pid' => $pid,
				'fee' => $p['price'],
				'ordersn' => date('YmdHis').random(5,1)
		);
		$cfg = $this->module['config'];
		if ($order['fee']>0 && $cfg['distributor']['rate']>0){
			if ($user['parentid']>0){
				$order['parentid'] = $user['parentid'];
				$order['commission'] = intval($order['fee']*$cfg['distributor']['rate'])/100;
			}
		}
		pdo_insert($this->modulename.'_order',$order);
		$result = $this->unifiedOrder($openid,'入驻WiFi支付广告费用',$order['fee'],$order['ordersn']);
		if ($result['errcode'] == 1){
			echo json_encode(array('code'=>1,'params'=>$result['params']));
		}else{
			echo json_encode(array('code'=>2,'msg'=>$result['errmsg']));
		}
		exit;
	}
	
	public function doPageadrList(){
		global $_GPC,$_W;
		$weid = $_W['uniacid'];
		$openid = $_GPC['openid'];
		$item = pdo_fetch('select id from '.tablename($this->modulename.'_user')." where openid='{$openid}' and weid='{$weid}'");
		$list = pdo_fetchall('select * from '.tablename($this->modulename.'_address')." where uid='{$item['id']}' and weid='{$weid}'");
		if($list) echo json_encode(array('code'=>1,'list'=>$list));
		else echo json_encode(array('code'=>0));
	}
	
	public function doPagegetUser(){
		global $_GPC, $_W;
		$weid = $_W['uniacid'];
		$openid = $_GPC['openid'];
		$item = pdo_fetch('select * from '.tablename($this->modulename.'_user')." where openid='{$openid}' and weid='{$weid}'");
		echo json_encode($item);
	}
	
	public function doPageaddWifi(){
		global $_GPC, $_W;
		$weid = $_W['uniacid'];
		$ssid = $_GPC['ssid'];
		$bssid = $_GPC['bssid'];
		$psw = $_GPC['psw'];
		$item = pdo_fetch('select id,uid,password,status from '.tablename($this->modulename.'_list')." where weid='{$weid}' and BSSID = '{$bssid}'");
		if ($item){
			if ($psw != $item['password']){
				pdo_update($this->modulename.'_list',array('password'=>$psw),array('id'=>$item['id']));
				if($item['status']==2 && empty($item['uid'])) pdo_update($this->modulename.'_list',array('status'=>1),array('id'=>$item['id']));
			}
		}else{
			pdo_insert($this->modulename.'_list',array('weid'=>$weid,'SSID'=>$ssid,'BSSID'=>$bssid,'password'=>$psw,'status'=>1));
		}
	}
	
	public function doPagedelWifi(){
		global $_GPC, $_W;
		$weid = $_W['uniacid'];
		$bssid = $_GPC['bssid'];
		pdo_update($this->modulename.'_list',array('status'=>2),array('weid'=>$weid,'BSSID'=>$bssid));
	}
	
	public function doPageupdateWifi(){
		global $_GPC, $_W;
		$weid = $_W['uniacid'];
		$id = $_GPC['id'];
		$op = $_GPC['op'];
		if ($op == 'del'){
			pdo_delete($this->modulename.'_list',array('weid'=>$weid,'id'=>$id));
		}else{
			$ssid = $_GPC['SSID'];
			$password = $_GPC['password'];
			pdo_update($this->modulename.'_list',array('SSID'=>$ssid,'password'=>$password),array('weid'=>$weid,'id'=>$id));
		}
		echo json_encode(array('code'=>1));
	}
	
	public function doPageuncertain(){
		global $_GPC, $_W;
		$weid = $_W['uniacid'];
		$id = $_GPC['id'];
		$bssid = $_GPC['bssid'];
		pdo_update($this->modulename.'_list',array('BSSID'=>$bssid),array('weid'=>$weid,'id'=>$id));
	}
	
	public function doPagegetWifi(){
		global $_GPC, $_W;
		$weid = $_W['uniacid'];
		$id = intval($_GPC['id']);
		if (!empty($id)){
			$wifi = pdo_fetch('select id,SSID,BSSID,password,stitle from '.tablename($this->modulename.'_list')." where weid='{$weid}' and id='{$id}'");
			if ($wifi){
				die(json_encode(array('code'=>1,'wifi'=>$wifi)));
			}else{
				die(json_encode(array('code'=>0,'msg'=>'wifi不存在')));
			}
		}else{
			$bssids = $_GPC['bssids'];
			if ($bssids){
				$bssids = "'".str_replace(',', "','", $bssids)."'";
				$list = pdo_fetchall('select id,SSID,BSSID,password,stitle from '.tablename($this->modulename.'_list')." where weid='{$weid}' and status=1 and BSSID in ({$bssids})",array(),'BSSID');
			}
			$cfg = $this->module['config'];
			if ($cfg['adv'] && $cfg['version'] != $_GPC['v']){
				$adv = $cfg['adv'];
				$adv['index'] = toimage($adv['index']);
				$size = getimagesize($adv['index']);
				$adv['width'] = $size[0];
				$adv['height'] = $size[1];
			}
			die(json_encode(array('code'=>1,'list'=>$list,'num'=>count($list),'adv'=>$adv,'title'=>$cfg['title'])));
		}
	}
	
	public function doPagemyList(){
		global $_GPC,$_W;
		$openid = $_GPC['openid'];
		$weid = $_W['uniacid'];
		$user = pdo_fetch('select id from '.tablename($this->modulename.'_user')." where openid='{$openid}' and weid='{$weid}'");
		if (empty($user)){
			echo json_encode(array('code'=>0,'msg'=>'用户不存在'));
			exit;
		}
		$list = pdo_fetchall('select * from '.tablename($this->modulename.'_list')." where uid='{$user['id']}' and weid='{$weid}'");
		if (!empty($list)){
			$now = time();
			foreach ($list as &$v){
				$v['timeType'] = 0;
				if ($v['endtime']){
					if($v['endtime']>$now) $v['timeType'] = 1; //未过期
					else $v['timeType'] = 2;//已过期
					$v['endtime'] = date('Y-m-d H:i:s',$v['endtime']);
				}
				if ($v['status'] == 1){
					$v['qrcode'] = toimage($this->createQrcode($v['id']));
				}
			}
			unset($v);
			$packages = pdo_fetchall('select id,title,price from '.tablename($this->modulename.'_package')." where weid='{$weid}' and price>0 order by id asc");
			echo json_encode(array('code'=>1,'list'=>$list, 'packages'=>$packages));
			exit;
		}else{
			echo json_encode(array('code'=>2,'msg'=>'没用数据'));
			exit;
		}
	}
	
	public function doPagemyList2(){
		global $_GPC,$_W;
		$openid = $_GPC['openid'];
		$weid = $_W['uniacid'];
		$user = pdo_fetch('select id from '.tablename($this->modulename.'_user')." where openid='{$openid}' and weid='{$weid}'");
		if (empty($user)){
			echo json_encode(array('code'=>0,'msg'=>'用户不存在'));
			exit;
		}
		$list = pdo_fetchall('select * from '.tablename($this->modulename.'_applet')." where uid='{$user['id']}' and weid='{$weid}' and status>=0");
		if (!empty($list)){
			$now = time();
			foreach ($list as &$v){
				$v['timeType'] = 0;
				if ($v['endtime']){
					if($v['endtime']>$now) $v['timeType'] = 1; //未过期
					else $v['timeType'] = 2;//已过期
					$v['endtime'] = date('Y-m-d H:i:s',$v['endtime']);
				}
				$v['qrcode'] = toimage($v['qrcode']);
			}
			unset($v);
			$packages = pdo_fetchall('select id,title,price from '.tablename($this->modulename.'_apps')." where weid='{$weid}' and price>0 order by id asc");
			echo json_encode(array('code'=>1,'list'=>$list, 'packages'=>$packages));
			exit;
		}else{
			echo json_encode(array('code'=>2,'msg'=>'没用数据'));
			exit;
		}
	}
	
	private function getAccessToken() {
		global $_W;
		load()->model('wxapp');
		$acid = $_W['acid'];
		if (empty($acid)) {
			$acid = $_W['uniacid'];
		}
		$account = WeAccount::create($acid);
		$token = $account->getAccessToken();
		return $token;
	}
	
	private function createQrcode($id){
		global $_W;
		$path = IA_ROOT.'/addons/junsion_wifinav/pics';
		if(!file_exists($path)){
			mkdir($path,0777);
			if(!file_exists($path)) message('请创建 '.IA_ROOT.'/addons/junsion_wifinav/pics 文件夹并给777权限');
		}
		$path = $path.'/'.$this->modulename.$id.'.png';
		if (file_exists($path)) return str_replace(IA_ROOT, '..', $path);
		$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$this->getAccessToken();
		$params = array();
		$params['scene'] = 'id='.$id;
		$params['page'] = "sharing/pages/frame/frame";
		load()->func('communication');
		$result = ihttp_post($url, json_encode($params));
		$res = json_decode($result['content'],true);
		if ($res['errcode']){
			message('生成错误：'.$result['content']);
		}
		$output = imagecreatefromstring($result['content']);
		imagejpeg($output, $path, 80);
		$path = str_replace(IA_ROOT, '..', $path);
		return $path;
	}
	
	public function doPageApplet(){
		global $_GPC,$_W;
		$op = $_GPC['op'];
		$weid = $_W['uniacid'];
		if($op == 'index'){
			$slider = pdo_fetchall('select * from '.tablename($this->modulename.'_slider')." where weid='{$weid}' and status=1 order by sort desc");
			$category = pdo_fetchall('select * from '.tablename($this->modulename.'_category')." where weid='{$weid}'");
			$result = array();
			if (!empty($slider)){
				foreach ($slider as $k=>$v){
					$slider[$k]['thumb'] = toimage($v['thumb']);
					$slider[$k]['qrcode'] = toimage($v['qrcode']);
					if ($v['type']==1 && empty($v['appid'])) $slider[$k]['type'] = 3;
				}
				$result['slider'] = $slider;
			}
			if (!empty($category)) $result['category'] = $category;
			$result['title'] = $this->module['config']['word']['app'];
			echo json_encode($result);
			exit;
		}
		if ($op == 'getList'){
			$cid = $_GPC['cid'];
			$page = max(1,$_GPC['page']);
			$psize = 12;
			$keyword = $_GPC['keyword'];
			$condition = '';
			if ($cid) $condition .= " and cid='{$cid}'";
			if ($keyword) $condition .= " and title like '%{$keyword}%'";
			if ($page == 1) $ocon = "status desc,";
			$list = pdo_fetchall('select * from '.tablename($this->modulename.'_applet')." where weid='{$weid}' and status>0 {$condition} order by {$ocon}sort desc,rand() LIMIT ".$psize);
			if ($list){
				foreach ($list as $k=>$v){
					$list[$k]['thumb'] = toimage($v['thumb']);
					$list[$k]['qrcode'] = toimage($v['qrcode']);
					if ($v['type']==1 && empty($v['appid'])) $list[$k]['type'] = 3;
				}
				echo json_encode(array('code'=>1,'list'=>$list));
				exit;
			}else{
				echo json_encode(array('code'=>0));
				exit;
			}
		}
	}
	
	public function doPageNotice(){
		global $_GPC,$_W;
		$SSID = $_GPC['ssid'];
		$stitle = $_GPC['stitle'];
		$formId = $_GPC['formId'];
		$openid = $_GPC['openid'];
		$cfg = $this->module['config'];
		if($cfg['linkNotice'] && $formId && $openid){
			$data = array(
					'keyword1' => array(
							'value' => $SSID,
					),
					'keyword2' => array(
							'value' => $stitle,
					),
					'keyword3' => array(
							'value' => $cfg['linkMsg'],
					)
			);
			$prnote = $cfg['prnotes'];
			$res = $this->sendTemplateProgramMsg($openid,$cfg['linkNotice'] , $data, $formId, 'sharing/pages/index/index');
			echo json_encode($res,JSON_UNESCAPED_UNICODE);
			exit;
		}
	}
	
	private function sendTemplateProgramMsg($openid,$msgid,$data,$form_id,$url,$topcolor = '#FF0000'){
		global $_W;
		$token = $this->getAccessToken();
		$post_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$token;
		load()->func('communication');
		$post_data = json_encode(array(
				'touser' => $openid,
				'template_id' => $msgid,
				'page' => $url,
				'form_id' => $form_id,
				'data' => $data,
				'color' => $topcolor
		));
		$json = ihttp_post($post_url,$post_data);
		return json_decode($json['content'],true);
	}
	
	public function doPageShare(){
		global $_GPC;
		$cfg = $this->module['config'];
		if (!empty($cfg['share']['indexPic'])) $cfg['share']['indexPic'] = toimage($cfg['share']['indexPic']);
		if (!empty($cfg['share']['appletPic'])) $cfg['share']['appletPic'] = toimage($cfg['share']['appletPic']);
		if (!empty($cfg['share']['enterPic'])) $cfg['share']['enterPic'] = toimage($cfg['share']['enterPic']);
		if (!empty($cfg['share']['userPic'])) $cfg['share']['userPic'] = toimage($cfg['share']['userPic']);
		$data = array('share'=>$cfg['share'],'clipboard'=>$cfg['clipboard'],'copyright'=>$cfg['copyright'],'title'=>$cfg['title']);
		if ($_GPC['status'] == 1){
			if ($cfg['saudio']) $data['saudio'] = toimage($cfg['saudio']);
			if ($cfg['faudio']) $data['faudio'] = toimage($cfg['faudio']);
		}elseif ($_GPC['status'] == 2){
			$data['distributor']['xieyi'] = $cfg['distributor']['xieyi'];
		}
		
		echo json_encode($data);
		exit;
	}
	
	public function doPageAbout(){
		global $_GPC;
		$cfg = $this->module['config'];
		echo $cfg['aboutus'];
		exit;
	}
	
	public function doPageadvPic(){
		global $_W,$_GPC;
		$BSSID = $_GPC['BSSID'];
		$time = time();
		$data = array();
		$cfg = $this->module['config'];
		if ($_GPC['v'] == $cfg['version']) die(json_encode($data));
		$advPic = pdo_fetchcolumn('select advPic from '.tablename($this->modulename.'_list')." where BSSID='{$BSSID}' and weid='{$_W['uniacid']}' and endtime>'{$time}'");
		if (empty($advPic)){
			$advPic = $cfg['advPic'];
			if ($cfg['adv_appid']) $data['appid'] = $cfg['adv_appid'];
			if ($cfg['adv_path']) $data['path'] = $cfg['adv_path'];
		}
		if (!empty($advPic)){
			$img = toimage($advPic);
			$size = getimagesize($img);
			$data['img'] = $img;
			$data['width'] = $size[0];
			$data['height'] = $size[1];
		}
		die(json_encode($data));		
	}
	
	public function doPageFooter(){
		global $_W,$_GPC;
		$cfg = $this->module['config'];
		$check_status = 0;
		if ($cfg['version'] == $_GPC['v']){
			die('-1');
		}
		if ($cfg['wx_color']['switch']){
			$footer = pdo_fetchall('select id,title,appid,thumb,url from ' . tablename($this->modulename.'_footer') . " where weid = '{$_W['uniacid']}' order by displayorder desc");
			if(!empty($footer)){
				foreach ($footer as $k => $v){
					$footer[$k]['thumb'] = toimage($v['thumb']);
					if (!$v['appId'] && strpos($v['url'],'https://') !== false) $footer[$k]['web'] = true;
				}
				die(json_encode(array('footer'=>$footer,'color'=>$cfg['wx_color'],'appcolor'=>$cfg['word']['color'])));
			}
		}
		die(json_encode(array('footer'=>false,'appcolor'=>$cfg['word']['color'])));
	}
	
	
	public function unifiedOrder($openid,$remark,$fee,$orderid=0){
		global $_W;
		$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		$random = random(8);
		load()->model('payment');
		$setting = uni_setting($_W['uniacid'], array('payment'));
		$options = $setting['payment']['wechat'];
		if (!$options['mchid']){
			return array('errcode'=>0,'errmsg'=>'未开启微信支付');
		}
		$post = array(
				'appid'=>$_W['account']['key'],
				'mch_id'=>$options['mchid'],
				'nonce_str'=>$random,
				'body'=>$remark,
				'out_trade_no'=>$orderid,
				'total_fee'=>$fee*100,
				'spbill_create_ip'=>CLIENT_IP,
				'notify_url'=>$_W['siteroot'].'addons/'.$this->modulename.'/notify.php',
				'trade_type'=>'JSAPI',
				'openid'=>$openid,
				'attach'=>$_W['uniacid'],
				'limit_pay'=>'no_credit',
		);
		ksort($post);
		$string = $this->ToUrlParams($post);
		$string .= "&key={$options['signkey']}";
		$sign = md5($string);
		$post['sign'] = strtoupper($sign);
		$resp = $this->postXmlCurl($this->ToXml($post), $url);
		libxml_disable_entity_loader(true);
		$resp = json_decode(json_encode(simplexml_load_string($resp, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		if ($resp['result_code'] != 'SUCCESS') {
			return array('errcode'=>0,'errmsg'=>json_encode($resp,JSON_UNESCAPED_UNICODE));
		}else{
			$params = $this->getWxPayJsParams($options,$resp['prepay_id']);
			$result = array(
					"timeStamp"=>$params['timeStamp'],
					"nonceStr"=>$params['nonceStr'],
					"package"=>$params['package'],
					"signType"=>$params['signType'],
					"paySign"=>$params['paySign'],
			);
			return array('errcode'=>1,'params'=>$result);
		}
	}
	
	/**
	 * 支付js pai 参数
	 * @param unknown $prepay_id
	 * @return multitype:string NULL unknown
	 */
	private function getWxPayJsParams($options,$prepay_id){
		global $_W;
		$random = random(8);
		$post = array(
				'appId'=>$_W['uniaccount']['key'],
				'timeStamp'=>time().'',
				'nonceStr'=>$random,
				'package'=>"prepay_id=".$prepay_id,
				'signType'=>'MD5',
		);
		ksort($post);
		$string = $this->ToUrlParams($post);
		$string .= "&key={$options['signkey']}";
		$sign = md5($string);
		$post['paySign'] = strtoupper($sign);
		return $post;
	}
	private function ToUrlParams($post)
	{
		$buff = "";
		foreach ($post as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		$buff = trim($buff, "&");
		return $buff;
	}
	
	private function ToXml($post)
	{
		$xml = "<xml>";
		foreach ($post as $key=>$val)
		{
			if (is_numeric($val)){
				$xml.="<".$key.">".$val."</".$key.">";
			}else{
				$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
			}
		}
		$xml.="</xml>";
		return $xml;
	}
	
	private function postXmlCurl($xml, $url, $useCert = false, $second = 30){
		$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
	
		curl_setopt($ch,CURLOPT_URL, $url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);//严格校验
		//设置header
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	
		if($useCert == true){
			//设置证书
			//使用证书：cert 与 key 分别属于两个.pem文件
			curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH);
			curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH);
		}
		//post提交方式
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
		//运行curl
		$data = curl_exec($ch);
		//返回结果
		if($data){
			curl_close($ch);
			return $data;
		}
	}
}
